#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2018-08-22 21:39:14
# @Author  : wanglele (18911756410@163.com)
# @Link    : None
# @Version : "Python 3.7"

import os
import sys

import itchat
import jieba
import matplotlib.pyplot as plt
import pandas as pd
from wordcloud import WordCloud


class WeChat:
    def __init__(self):
        itchat.login()
        self.friends = itchat.get_friends(update=True)[0:]
        plt.rcParams["font.sans-serif"] = ["SimHei"]
        plt.rcParams["axes.unicode_minus"] = False
        # print(self.friends)  # 朋友信息
        # print(self.friends[0])  # 自己的信息

    def save_info(self, NickName, Sex, Province, City, Signature):
        """
        保存朋友信息        
        Arguments:
            NickName: 昵称
            Sex: 性别
            Province:  省份
            City: 城市
            Signature: 签名        
        Returns:
            列表，字典元素，每个朋友信息是一个字典
        """
        list = []
        for i in self.friends:
            dict = {}
            dict["NickName"] = i[NickName]
            if i[Sex] == 2:
                dict["Sex"] = "女"
            elif i[Sex] == 1:
                dict["Sex"] = "男"
            else:
                dict["Sex"] = "不明"
            dict["Province"] = i[Province]
            dict["City"] = i[City]

            dict["Signature"] = (
                i[Signature]
                .strip()
                .replace("span", "")
                .replace("class", "")
                .replace("emoji", "")
                .replace("\n", "")
            )
            list.append(dict)
        return list

    def save_csv(self):
        args = ("NickName", "Sex", "Province", "City", "Signature")
        list = self.save_info(*args)
        pf = pd.DataFrame(list)
        try:
            pf.to_csv("wechat.csv", index=True, encoding="gb18030")
        except Exception as e:
            print(e)
        return pf

    def anysys(self, pf):
        """
        pandas的value_counts()方法可以统计每种性别和每个省份出现的次数，并由大到小排序，这里我们提取省份前15个，并转成dataframe结构,由于有些省份没有填写，为空，通过遍历，将空的省份替换成“未知”
        """
        res_sex = pd.DataFrame(pf["Sex"].value_counts())  # 性别分布
        res_province = pd.DataFrame(
            pf["Province"].value_counts()[:15])  # 前15个省份分布
        res_signature = pd.DataFrame(pf["Signature"][:50])  # 前50个签名
        index_list = []
        for i in list(res_province.index):
            if i == "":
                i = "未知"
            index_list.append(i)

        res_province.index = index_list
        print(
            "性别：%s \n 省份：%s \n 签名：%s \n %s \n %s \n %s \n"
            % (
                res_sex,
                res_province,
                res_signature,
                type(res_province),
                type(res_sex),
                type(res_signature),
            )
        )
        return res_sex, res_province, res_signature

    def get_chart(
        self, train_data, feature_list, x_feature, chart_type, width_bar=None
    ):
        """折线图、散点图、条形图绘制

        [description]

        Arguments:
            train_data ： DataFrame类型
            feature_list ：特征列表
            x_feature ： 特征，要统计的x轴的数据类别名称
            chart_type ： 0 折线图  1 散点图  2 条形图

        Keyword Arguments:
            width_bar ： num 类型。条形图的宽度，必须传值
        """
        pass

    def get_sign(self, res_signature):
        res_signature.dropna(axis=0, inplace=True)
        print("111111111", res_signature)
        cut_words_list = []
        for i in res_signature["Signature"]:
            cut_words = list(jieba.cut(i))
            print(222, cut_words)
            cut_words_list.extend(cut_words)

        print("cut_words_list", cut_words_list)
        stop_words = pd.read_table("stopwords_dict.txt")
        print("stop_words", stop_words)
        for i in stop_words:
            if i in cut_words_list:
                cut_words_list.remove(i)
        print("cut_words_list11", cut_words_list)
        print(len(cut_words_list))

        k_list = []
        v_list = []
        for k, v in Counter(cut_words_list).items():
            k_list.append(k)
            v_list.append(v)
        print(k_list, v_list, len(k_list), len(v_list))
        return k_list, v_list

    def wordcloud(self, x, y, label):
        wordcloud = WordCloud(width=1300, height=640)
        wordcloud.add(label, x, y, word_size_range=[20, 100], shape="start")
        wordcloud.render()
        os.system(r"render.html")


if __name__ == "__main__":
    wx = WeChat()
    pf = wx.save_csv()
    anysys = wx.anysys(pf)
    # wx.get_sign(anysys[2])
